<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>视频上传</title>


    <script src="/admin/html/module/videoUpload/jquery-demo/lib/aliyun-upload-sdk/aliyun-upload-sdk-1.5.3.min.js"></script>
    <script src="/admin/html/module/videoUpload/jquery-demo/lib/aliyun-upload-sdk/lib/es6-promise.min.js"></script>
    <script src="/admin/html/module/videoUpload/jquery-demo/lib/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min.js"></script>

    <link rel="stylesheet" href="/admin/plugin/layui/dist/css/layui.css" tppabs="http://res.layui.com/layui/dist/css/layui.css"  media="all">
    <script src="/admin/plugin/layui/dist/layui.js" charset="utf-8"></script>

    <script type="text/javascript" src="/admin/js-css/js/vue.min.js"></script>
    <script type="text/javascript" src="/admin/js-css/js/mx1.0.js?v=1.2"></script>
</head>
<body>

<div id="app">


    <div class="layui-btn-group" style="margin: 5px 10px;" >
        <button class="layui-btn layui-btn-normal layui-btn-sm" @click="addVideo" >增加</button>
    </div>


    <span v-if="kcmc != null">当前课程：{{kcmc}}</span>
    <table class="layui-table">
        <colgroup>
            <col width="150">
            <col width="150">
            <col width="200">
            <col>
        </colgroup>
        <thead>
        <tr>
            <th style="width: 300px;">标题</th>
            <th>排序号</th>
            <th>上传时间</th>
            <th>是否免费</th>
            <th>视频状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,index) in list">
            <td><input type="text" v-model="list[index].title" placeholder="请输入视频标题" autocomplete="off" class="layui-input"></td>
            <td><input type="text" v-model="list[index].pxh" placeholder="请输入排序号" autocomplete="off" class="layui-input"></td>
            <td>{{item.sj}}</td>
            <td>
                <select  class="layui-input" v-model="list[index].ismf" >
                    <option value="0">收费</option>
                    <option value="1">免费</option>
                </select>
            </td>
            <td :tzt="item.id" v-if="item.isupload == 0" >未上传</td>
            <td :tzt="item.id" v-if="item.isupload == 1" >上传完成</td>
            <td>
                <input type="file" :id="item.id" :index="index" style="display: none;" :UploadAuth="item.UploadAuth" :UploadAddress="item.UploadAddress" :videoId="item.alispid" >
                <button class="layui-btn layui-btn-normal layui-btn-sm" @click="uploadFile(item.id)" :up="item.id" >上传视频</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm"  @click="vm.delete(item.id)">删除</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm"  @click="vm.getOnDemandPath(item.id)">点播</button>
            </td>
        </tr>


        </tbody>
    </table>
</div>

<script>
    var $ = null;
    var vm = new Vue({
        el: '#app',
        data:{
            region:"cn-shanghai",
            userId:"1327249998895500",
            list:[],
            kcmc:""
        },
        created(){
            this.init();
        },
        methods:{
            init(){
                layui.use(['form','jquery'], function(){
                    $ = layui.jquery;
                    vm.ieinit();
                    vm.initFiles();
                })
            },
            uploadOver(id){
                post("/admin/api/VideoManagementController/uplodOver",{id:id},function (res) {
                    let index = $("#"+id).attr("index");
                    vm.list[index].isupload = "1";
                })
            },
            delete(id){
                post("/admin/api/VideoManagementController/delete",{id:id},function (res) {
                    top.alert(res.msg);
                    let index = $("#"+id).attr("index");
                    vm.list.splice(index,1);
                })
            },
            getOnDemandPath(id){
                post("/admin/api/VideoManagementController/getOnDemandPath",{id:id},function (res) {
                    if(res.code == 0){
                        top.alert(res.msg);
                        return;
                    }
                    top.f_layer_open_get(res.data,"90%","80%",function () {

                    },null,"视频点播");
                })
            },
            initFiles(){
                $("[type=file]").each(function (index) {
                    $(this).on('change', function (e) {
                        var file = e.target.files[0]
                        if (!file) {
                            alert("请先选择需要上传的文件!")
                            return
                        }
                        let userData = '{"Vod":{}}'
                        let uploader = vm.createUploader($(this).attr("id"));
                        // 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)
                        console.log(uploader)
                        uploader.addFile(file, null, null, null, userData);
                        uploader.startUpload();
                    })
                });
            },
            addVideo(){
                let param = top.data.param;
                let i = load()
                post("/admin/api/VideoManagementController/add",{kcids:param.ids},function (res) {
                    layer.close(i);
                    if(res.code == 0){
                        top.alert(res.msg);
                        return;
                    }
                    vm.list.push(res.data);
                    vm.$nextTick(function () {
                        vm.initFiles();
                    })

                })
            },
            uploadFile(c){
                $("#"+c).click();
            },
            createUploader (id) {
                var uploader = new AliyunUpload.Vod({
                    timeout: 60000,
                    partSize: 1048576,
                    parallel: 5,
                    retryCount: 3,
                    retryDuration: 2,
                    region: vm.region,
                    userId: vm.userId,
                    // 添加文件成功
                    addFileSuccess: function (uploadInfo) {
                        $("[tzt="+id+"]").text('添加文件成功, 等待上传...')
                        console.log("addFileSuccess: " + uploadInfo.file.name)
                    },
                    // 开始上传
                    onUploadstarted: function (uploadInfo) {
                        // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
                        // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
                        // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
                        // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
                        // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
                        // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
                        var uploadAuth = $("#"+id).attr("UploadAuth");
                        var uploadAddress = $("#"+id).attr("UploadAddress");
                        var videoId = $("#"+id).attr("videoId");
                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
                        $("[tzt="+id+"]").text('文件开始上传...')


                    },
                    // 文件上传成功
                    onUploadSucceed: function (uploadInfo) {
                        console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
                        $("[tzt="+id+"]").text('上传完成');
                        vm.uploadOver(id);
                    },
                    // 文件上传失败
                    onUploadFailed: function (uploadInfo, code, message) {
                        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
                        $("[tzt="+id+"]").text('文件上传失败');
                    },
                    // 取消文件上传
                    onUploadCanceled: function (uploadInfo, code, message) {
                        console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
                        $("[tzt="+id+"]").text('文件上传已暂停!')
                    },
                    // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
                    onUploadProgress: function (uploadInfo, totalSize, progress) {
                        console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
                        var progressPercent = Math.ceil(progress * 100)
                        $("[tzt="+id+"]").text('上传进度：'+progressPercent+"%");
                    },
                    // 上传凭证超时
                    onUploadTokenExpired: function (uploadInfo) {
                        // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                        // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                        // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                        $("[tzt="+id+"]").text('文件上传超时!')

                        let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
                        $.get(refreshUrl, function (data) {
                            var uploadAuth = data.UploadAuth
                            uploader.resumeUploadWithAuth(uploadAuth)
                            console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
                        }, 'json')
                    },
                    // 全部文件上传结束
                    onUploadEnd: function (uploadInfo) {
                        $("[tzt="+id+"]").text('上传完成')
                        console.log("onUploadEnd: uploaded all the files")
                    }
                })
                return uploader;
            },
            ieinit(){
                //兼容IE11
                if (!FileReader.prototype.readAsBinaryString) {
                    FileReader.prototype.readAsBinaryString = function (fileData) {
                        var binary = "";
                        var pt = this;
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var bytes = new Uint8Array(reader.result);
                            var length = bytes.byteLength;
                            for (var i = 0; i < length; i++) {
                                binary += String.fromCharCode(bytes[i]);
                            }
                            //pt.result  - readonly so assign binary
                            pt.content = binary;
                            pt.onload()
                        }
                        reader.readAsArrayBuffer(fileData);
                    }
                }
            }
        }
    });


    function verification () {
        let list = vm.list;
        for(let a=0;a<list.length;a++){
            let item = list[a];
            if(item.title == ""){
                top.alert("标题不能为空!");
                return false;
            }
            if(item.isupload == "0"){
                top.alert("还有待上传的视频，不能保存");
                return false;
            }
        }
        return true;
    }

    function setData(map) {
        vm.kcmc = map.names;
        vm.list = map.list;
    }
    function getData() {
        let mapdata = {mapdata:vm.list};
        return mapdata;
    }

</script>
</body>
</html>
